package com.cdbkj.cloud.pos.fragment;


import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;

import com.androidyang.library.common.adapter.CommonAdapter;
import com.androidyang.library.common.adapter.Wrapper;
import com.androidyang.library.http.okhttp.bean.HttpResult;
import com.androidyang.library.http.okhttp.listener.HttpClientHandler;
import com.cdbkj.cloud.pos.http.HttpRequest;
import com.cdbkj.cloud.pos.utils.PageUtil;
import com.cdbkj.cloud.pos.R;
import com.cdbkj.cloud.pos.bean.JsonResult;
import com.cdbkj.cloud.pos.utils.Tools;

import java.util.List;
import java.util.Map;

/**
 * 选择处方 处方列表页面
 */
public class PrescriptionFragment extends Fragment implements HttpClientHandler, AdapterView.OnItemClickListener, View.OnClickListener {
    private static final String ARG_PARAM1 = "patientId";
    private static final String ARG_PARAM2 = "userId";
    private static final String ARG_PARAM3 = "registerNo";
    protected View rootView;
    protected ListView mListView;

    private String patientId;
    private String userId;
    private String registerNo;

    private ListAdapter adapter;
    private List<Map> list;
    private int pageSize = 5;
    private int curPage = 1;
    private Button prevBtn;
    private Button nextBtn;
    private TextView pageText;
    private int totalPage = 0;

    private OnPrescriptionFragmentInteractionListener mListener;

    public PrescriptionFragment() {
        // Required empty public constructor
    }

    public static PrescriptionFragment newInstance(String patientId, String userId) {
        PrescriptionFragment fragment = new PrescriptionFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, patientId);
        args.putString(ARG_PARAM2, userId);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            patientId = getArguments().getString(ARG_PARAM1);
            userId = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnPrescriptionFragmentInteractionListener) {
            mListener = (OnPrescriptionFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_prescription, container, false);
        initView(rootView);
        return rootView;
    }

    private void initView(View rootView) {
        mListView =  rootView.findViewById(R.id.listView);
        prevBtn =  rootView.findViewById(R.id.prev_page_btn);
        nextBtn = rootView.findViewById(R.id.next_page_btn);
        pageText = rootView.findViewById(R.id.page_text);
        prevBtn.setOnClickListener(this);
        nextBtn.setOnClickListener(this);
        prevBtn.setEnabled(false);
        nextBtn.setEnabled(false);
        mListView.setOnItemClickListener(this);

        HttpRequest.prescriptionList("prescriptionList",this,registerNo,patientId,userId);
        adapter = new ListAdapter(getActivity(), null);
        mListView.setAdapter(adapter);
    }

    @Override
    public void httpClientSuccess(Object o, HttpResult httpResult) {
        JsonResult json = (JsonResult) httpResult.getResult();
        if (json == null) {
            //ToastUtils.showShort(getActivity(),"服务器处理异常");
            Tools.showDialogWithReturnMainActivity("服务器处理异常",getActivity());
        }
        if (!json.isSuccess()) {
            //ToastUtils.showShort(getActivity(),json.getMsg());
            Tools.showDialogWithReturnMainActivity(json.getMsg(),getActivity());
            return;
        }
        list = (List) json.getData();
        totalPage = PageUtil.getTotalPage(list.size(),pageSize);
        List result = PageUtil.handelPage(list,curPage,pageSize,pageText,nextBtn,prevBtn);
        adapter.setList(result,true);
    }

    @Override
    public void httpClientError(Object o, HttpResult httpResult) {
        //ToastUtils.showShort(getActivity(),"网络异常");
        Tools.showDialogWithReturnMainActivity("网络连接异常，请联系管理员！",getActivity());
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        Map item = (Map) adapterView.getAdapter().getItem(i);
        if(item.get("prescriptionSeq")==null){
            //ToastUtils.showShort(getActivity(),"HIS数据错误，无处方号");
            Tools.showDialogWithReturnMainActivity("HIS数据错误，无处方号",getActivity());
            return;
        }
        if(item.get("presDate")==null){
            //ToastUtils.showShort(getActivity(),"HIS数据错误，无处处方日期");
            Tools.showDialogWithReturnMainActivity("HIS数据错误，无处处方日期",getActivity());
            return;
        }
        mListener.onPrescriptionFragmentInteraction(item.get("presDate").toString(),item.get("prescriptionSeq").toString());
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.prev_page_btn:
                if((curPage-1)>0){
                    curPage--;
                    List result = PageUtil.handelPage(list,curPage,pageSize,pageText,nextBtn,prevBtn);
                    adapter.setList(result,true);
                }
                break;
            case R.id.next_page_btn:
                if((curPage+1)<=totalPage){
                    curPage++;
                    List result2 = PageUtil.handelPage(list,curPage,pageSize,pageText,nextBtn,prevBtn);
                    adapter.setList(result2,true);
                }
                break;
            default:
                break;
        }
    }


    class ListAdapter extends CommonAdapter<Map> implements View.OnClickListener {

        public ListAdapter(Context context, List<Map> list) {
            super(context, R.layout.item_prescription, list);
        }

        @Override
        public void convert(Wrapper<Map> wrapper, Map item) {
            wrapper.setText(R.id.recipeSEQ_tv, (String) item.get("prescriptionSeq"));
            wrapper.setText(R.id.deptName_tv,(String) item.get("departmentName"));
            wrapper.setText(R.id.fee_tv,(String) item.get("fee"));
            wrapper.setText(R.id.presDate_tv,(String) item.get("presDate"));

            ImageButton payBtn = wrapper.getView(R.id.pay_btn);
            payBtn.setTag(item);
            payBtn.setOnClickListener(this);
        }

        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.pay_btn:
                    Map item = (Map) view.getTag();
                    if(item.get("prescriptionSeq")==null){
                        //ToastUtils.showShort(getActivity(),"HIS数据错误，无处方号");
                        Tools.showDialogWithReturnMainActivity("HIS数据错误，无处方号",getActivity());
                        return;
                    }
                    if(item.get("fee")==null){
                        //ToastUtils.showShort(getActivity(),"HIS数据错误，费用缺失");
                        Tools.showDialogWithReturnMainActivity("HIS数据错误，费用缺失",getActivity());
                        return;
                    }
                    mListener.toPayWay(item.get("prescriptionSeq").toString(),item.get("fee").toString());
                    break;
            }
        }
    }

    public interface OnPrescriptionFragmentInteractionListener {
        void onPrescriptionFragmentInteraction(String presDate,String prescriptionSeq);
        void toPayWay(String prescriptionSeq,String cost);
    }
}
